/**
 * Created by Amaris on 2016/12/6.
 */
var async = require('async');
var util = require('../utils/util.js');
var roadshowClass = require('../class/roadshow.js');
var stockRecommend = require('../controller/controller.stockrecommend');

var userjoinCtrl = require('../controller/controller.userjoin.js');

module.exports = {

    create: function (params, cb) {
        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var roadshow = new roadshowClass();
        /**
         *
         */
        params.companyRecommend = '0';
        var analystType = params.analystType;
        if (analystType == 'company') {
            params.companyRecommend = '1';
        }
        var checkResult = roadshow.checkParams(
            [
                'seller',
                'industry',
                'startTime',
                'finishTime',
                'type',
                'createUid'
            ], params);
        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {
            roadshow.init(params);
        }

        models.roadshow.create(roadshow.getParams(), function (err, data) {
            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }

            var actionId = data.rowId;
            if (analystType == 'company') {
                var stockList = params.stockList;

                for (var i = 0; i < stockList.length; i++) {

                    stockList[i].actionId = actionId;
                    stockList[i].actionType="mconference";

                }
                roadshow.init(params);
                stockRecommend.create(stockList, function (err, result) {
                    if (err) {
                        handleError(res, err);
                    } else {
                        console.log(roadshow.getParams());
                        data.companyRecommend = result;
                        cb(null, util.getSuccessRes(data));
                    }
                });
            } else {
                cb(null, util.getSuccessRes(data));
            }


        });


    },
    update: function (params, cb) {
        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var roadshow = new roadshowClass();
        var checkResult = roadshow.checkParams(['rowId'], params);
        var checkScore = roadshow.checkParams(['score'], params);

        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {

            if (!checkScore) {

                var now = new Date();
                var jsonDate = now.toJSON();
                var then = new Date(jsonDate);
                params.scoreTime = then;
            }

            roadshow.init(params);
        }


        models.roadshow.update({rowId: params.rowId}, roadshow.getParams()).exec(function (err, data) {
            if (err || !data) {
                console.log(err);
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }

            cb(null, util.getSuccessRes(data));
        });
    },
    //此接口增加userId参数
    getInfo: function (params, cb) {
        var models = util.models;

        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var roadshow = new roadshowClass();

        var checkResult = roadshow.checkParams(['rowId'], params);
        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {
            roadshow.init(params);
        }
        async.series({

            roadshowInfo: function (callback) {
                models.roadshow.findOne(roadshow.getParams()).populate('seller').populate('createUid').populate('industry').populate('address').populate('scoreUid').exec(function (err, data) {
                    if (err || !data) {
                        var err = new Error();
                        err.status = 500;
                        err.message = '系统错误';
                        cb(err, null);
                        return;
                    }

                    var companyRecommend = data.companyRecommend;
                    var createUid = data.createUid.createUid;
                    if (companyRecommend == '1') {
                        stockRecommend.getListByCreateUid({createUid: createUid,actionId:data.rowId}, function (err, result) {
                            if (err) {
                                callback(res, err);
                            } else {
                                data.companyRecommend = result.obj;
                                callback(null, data);
                            }
                        })
                    } else {
                        callback(null, data);
                    }

                });
            },
            userjoinList: function (callback) {
                if (params.rowId) {
                    userjoinCtrl.getUserJoinListByActionId({
                        actionId: params.rowId
                    }, function (err, result) {

                        if (err) {
                            callback(null, err);
                        } else {
                            callback(null, result.obj);
                        }
                    });
                } else {
                    callback(null, null);
                }

            },
            userjoinInfo: function (callback) {
                if (params.userId) {
                    userjoinCtrl.getUserJoinInfoByUserIdActionId({
                        actionId: params.rowId,
                        userId: params.userId
                    }, function (err, result) {

                        if (err) {
                            callback(null, err);
                        } else {
                            callback(null, result.obj);
                        }
                    });
                } else {
                    callback(null, null);
                }
            },

        }, function (err, results) {
            if (err) {
                handleError(res, err);
            } else {
                if (results.roadshowInfo) {

                    results.roadshowInfo.userjoinInfo = results.userjoinInfo;
                    results.roadshowInfo.userjoinList = results.userjoinList;
                }
                cb(null, util.getSuccessRes(results.roadshowInfo));
            }
        });

    },
    getList: function (params, cb) {

        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var roadshow = new roadshowClass();
        var checkResult = roadshow.checkParams(['createUid'], params);
        var expr = {};
        if (!checkResult) {
            roadshow.init(params);
            var checkTime = roadshow.checkParams(['startTime', 'finishTime'], params);
            if (checkTime) {
                expr = {
                    createUid: roadshow.getParam('createUid')
                }
            } else {
                expr = {
                    or: [
                        {
                            startTime: {
                                '>=': new Date(roadshow.getParam('startTime')),
                                '<=': new Date(roadshow.getParam('finishTime'))
                            }
                        }, {
                            finishTime: {
                                '>=': new Date(roadshow.getParam('startTime')),
                                '<=': new Date(roadshow.getParam('finishTime'))
                            }
                        }
                    ],
                    createUid: roadshow.getParam('createUid')
                }
            }


        } else {
            roadshow.init(params);
            var checkTime = roadshow.checkParams(['startTime', 'finishTime'], params);
            if (!checkTime) {
                expr = {
                    or: [
                        {
                            startTime: {
                                '>=': new Date(roadshow.getParam('startTime')),
                                '<=': new Date(roadshow.getParam('finishTime'))
                            }
                        }, {
                            finishTime: {
                                '>=': new Date(roadshow.getParam('startTime')),
                                '<=': new Date(roadshow.getParam('finishTime'))
                            }
                        }, {
                            startTime: {
                                '<=': new Date(roadshow.getParam('startTime')),

                            },
                            finishTime: {
                                '>=': new Date(roadshow.getParam('finishTime'))
                            }
                        }
                    ]}
            }
        }

        var checkSeller = roadshow.checkParams(['seller'], params);
        if(!checkSeller){
            expr.seller=roadshow.getParam('seller');
        }

        models.roadshow.find(expr).populate('seller').populate('address').populate('createUid').populate('industry').exec(function (err, data) {

            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }
            cb(null, util.getSuccessRes(data));
        });
    },

    /**
     * 根据Id获取路演列表
     * @param params
     * @param cb
     */
    getListByIds: function (params, cb) {

        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var roadshow = new roadshowClass();
        var checkResult = roadshow.checkParams(['createUid'], params);
        var expr = {};
        if (!checkResult) {
            roadshow.init(params);
            var checkTime = roadshow.checkParams(['startTime', 'finishTime'], params);
            if (checkTime) {
                expr = {

                    createUid: roadshow.getParam('createUid'),
                    rowId:  params.rowIdArr

                }
            } else {
                expr = {
                    or: [
                        {
                            startTime: {
                                '>=': new Date(roadshow.getParam('startTime')),
                                '<=': new Date(roadshow.getParam('finishTime'))
                            }
                        }, {
                            finishTime: {
                                '>=': new Date(roadshow.getParam('startTime')),
                                '<=': new Date(roadshow.getParam('finishTime'))
                            }
                        }, {
                            startTime: {
                                '<=': new Date(roadshow.getParam('startTime')),

                            },
                            finishTime: {
                                '>=': new Date(roadshow.getParam('finishTime'))
                            }
                        }
                    ],

                    createUid: roadshow.getParam('createUid'),
                    rowId: params.rowIdArr

                }
            }

        } else {
            roadshow.init(params);
            var checkTime = roadshow.checkParams(['startTime', 'finishTime'], params);
            if (!checkTime) {
                expr = {
                    or: [
                        {
                            startTime: {
                                '>=': new Date(roadshow.getParam('startTime')),
                                '<=': new Date(roadshow.getParam('finishTime'))
                            }
                        }, {
                            finishTime: {
                                '>=': new Date(roadshow.getParam('startTime')),
                                '<=': new Date(roadshow.getParam('finishTime'))
                            }
                        }, {
                            startTime: {
                                '<=': new Date(roadshow.getParam('startTime')),

                            },
                            finishTime: {
                                '>=': new Date(roadshow.getParam('finishTime'))
                            }
                        }
                    ],
                    rowId: params.rowIdArr
                }
            }
        }

        models.roadshow.find(expr).populate('seller').populate('address').populate('createUid').populate('industry').exec(function (err, data) {

            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }
            cb(null, util.getSuccessRes(data));
        });
    },
    getListBySeller: function (params, cb) {

        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = "数据库连接失败";
            cb(err, null);
            return;
        }
        var roadshow = new roadshowClass();

        var checkResult = roadshow.checkParams(['seller'], params);
        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {
            roadshow.init(params);
        }
        models.roadshow.find(roadshow.getParams()).populate('seller').populate('createUid').populate('industry').exec(function (err, data) {

            if (err || !data) {
                var err = new Error();
                err.status = 500;
                err.message = '系统错误';
                cb(err, null);
                return;
            }

            cb(null, util.getSuccessRes(data));
        });

    },

    delete: function (params, cb) {
        var models = util.models;
        if (!models) {
            var err = new Error();
            err.status = 500;
            err.message = '数据库连接失败';
            cb(err, null);
            return;
        }

        var roadshow = new roadshowClass();

        var checkResult = roadshow.checkParams(['rowId'], params);
        if (checkResult) {
            cb(null, util.getErrorRes('400', checkResult));
            return;
        } else {
            roadshow.init(params);
        }

        var rowId = params.rowId;
        models.roadshow.destroy({'rowId': rowId}).exec(function (err, data) {
            if (err || !data) {
                cb(err, null);
                return;
            }
            if (data && data.length == 0) {
                var err = new Error();
                err.status = 500;
                err.message = '删除失败';
                cb(err, null);
                return;
            }
            cb(null, util.getSuccessRes(data));
        });
    }
};
